import { defineStore } from 'pinia'
import { onMounted, onUnmounted} from 'vue'

export const useTodoStore = defineStore('todo', {
  state: () => {
    // 尝试从本地存储获取数据
    let savedState = null
    try {
      const saved = uni.getStorageSync('todo-store')
      if (saved) {
        savedState = JSON.parse(saved)
      }
    } catch (e) {
      console.error('读取存储数据失败：', e)
    }

    return {
      list: savedState?.list || [
        {id:'0',title:'点击此处可以展开详细信息',isFinish:'1',time:'',isColor:false,show:'none',isdelete:true},
        {id:'1',title:'右滑可以快捷完成事项',isFinish:'1',time:'',isColor:false,show:'none',isdelete:true},
        {id:'2',title:'左滑可以快速编辑该事项',isFinish:'1',time:'',isColor:false,show:'none',isdelete:true},
        {id:'3',title:'这里也可以展示时间',isFinish:'1',time:'上午07:30',isColor:false,show:'none',isdelete:true},
        {id:'4',title:'当然这样里也可以添加不同颜色标签',isFinish:'1',time:'',isColor:true,show:'none',isdelete:true},
        {id:'5',title:'点击这里GET更多技能吧',isFinish:'1',time:'',isColor:false,show:'none',isdelete:true},
      ],
      timer: null // 添加定时器状态
    }
  },

  actions: {
    // 删除方法
    handleDelete(id) {
      this.list = this.list.map(item => {
        if (item.id === id) {
          return { ...item, show: 'right', isdelete: false }
        }
        return item
      })
      this.saveToStorage()
    },

    // 确认删除
    listDelete(id) {
	    // 使用深拷贝
	    this.list = JSON.parse(JSON.stringify(
	      this.list.filter(item => String(item.id) !== String(id))
	    ))
	    this.saveToStorage()
    },
	
	// 添加
	addTodo(todo) {
	   // 使用深拷贝
	     const newTodo = JSON.parse(JSON.stringify({
	       ...todo,
	       id: String(Date.now())
	     }))
	     this.list.push(newTodo)
	     this.saveToStorage()
	  },
	  
    // 完成事项
    handleFinish(id) {
      const target = this.list.find(item => item.id === id)
      if (target) {
        target.isFinish = '2'
        this.saveToStorage()
      }
    },
	
	// // 处理滑块状态
	// handleSwipeChange(id,e){
	// 	if(e==='none'){
	// 	this.list = this.list.map(item => {
	// 	if (item.id === id) {
	//     return { ...item, show:'none', isdelete: true }
	// 		}
	// 	return item
	// 	 this.saveToStorage()
	// 	})
	//  }
	// },

    // 保存到本地存储
    saveToStorage() {
      try {
        uni.setStorageSync('todo-store', JSON.stringify({
          list: this.list
        }))
        // 发送数据变化事件
        uni.$emit('todo-data-changed', this.list)
      } catch (e) {
        console.error('保存数据失败：', e)
      }
    },

    // 初始化事件监听
    initEventListeners() {
      uni.$on('todo-data-changed', (newList) => {
        this.list = newList
      })
    },

    // 清理事件监听
    removeEventListeners() {
      uni.$off('todo-data-changed')
    }
  }
}) 